package com.warmlight.voicepacket.ui.imlm;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.RecordActivity;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.eventbus.Login;
import com.warmlight.voicepacket.data.eventbus.TeaseRelease;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.HttpUtils;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.ui.imlm.adapter.GoodListenerTeaseViewpagerAdapter;
import com.warmlight.voicepacket.ui.user.LoginRegistActivity;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class GoodListenerTeaseActivity extends BaseActivity implements View.OnClickListener {

    ViewPager mViewPager;
//    List<Fragment> mFragments;

    private TabLayout mTabLayout;
    private ArrayList<Map<String, String>> tabs;
    private GoodListenerTeaseViewpagerAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_good_listener_tease);

        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mTabLayout = (TabLayout) findViewById(R.id.tabs);
        initView();
        setupViewPager();
        loadData();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void xxx(Login login){

        loadData();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void teaseRelease(TeaseRelease teaseRelease){
        loadData();
    }

    /**
     * "data": {
     "tab": [{
     "id": 0,
     "title": "最热"
     },
     {
     "id": 1,
     "title": "最新"
     },
     {
     "id": 2,
     "title": "我的"
     }
     ],
     "has_more": true,
     "list": [{
     "id": "1",
     "type": "1",
     "title": "玩皮凉鞋正品真皮男士休闲鞋",
     "url": "https:\/\/wanpi-img.oss-cn-shanghai.aliyuncs.com\/wanpi_audio/1001/20180807192637/avator.pcm",
     "duration": "0",
     "is_hot": "0",
     "is_like": false,
     "star_num": "0",
     "add_time": "08-07 11:26",
     "author": {
     "uid": "1001",
     "nickname": "波",
     "avator": "https:\/\/wanpi-img.oss-cn-shanghai.aliyuncs.com\/wanpi\/1001\/20180807212451\/avator.png"
     }
     }]
     }
     */
    private void loadData() {
        String url = HttpConfig.GOODLISTENERTEASE;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("category","0");
        treeMap.put("page","1");
        treeMap.put("pagesize","10");
        HttpClient.getInstance().postRxAndroidAES(url,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (HttpUtils.isCodeSuccess(responseData.getCode())){
                            String data = responseData.getData();
                            ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(data);
                            Map<String, String> map = listMapByJson.get(0);
                            String tab = map.get("tab");
                            ArrayList<Map<String, String>> tabList = JSONUtils.getListMapByJson(tab);
                            setTabs(tabList);
                        }else{

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void setTabs(ArrayList<Map<String, String>> tabList){
        Bundle extras = getIntent().getExtras();
        int item = 0;
        if (extras != null){
            if (extras.containsKey("jump_page")){
                String jump_page = extras.getString("jump_page");
                if (TextUtils.equals("3",jump_page)){
                    for (int i=0;i<tabList.size();i++){
                        Map<String, String> map = tabList.get(i);
                        if (TextUtils.equals("我的",map.get("title"))){
                            item = i;
                            break;
                        }
                    }
                }
            }
        }
        tabs.clear();
        tabs.addAll(tabList);
        adapter.notifyDataSetChanged();
        if (item > 0){
            mViewPager.setCurrentItem(item,false);
        }
    }

    private void initView() {
        setBack();
//        LinearLayout ll_back = findViewById(R.id.ll_back);
        LinearLayout ll_right = findViewById(R.id.ll_right);
        ll_right.setOnClickListener(this);
    }


    private void setupViewPager() {

//        mFragments = new ArrayList<>();
//        for (int i = 0; i < mTitles.length; i++) {
//            ListFragment listFragment = ListFragment.newInstance(mTitles[i]);
//            mFragments.add(listFragment);
//        }
        // 第二步：为ViewPager设置适配器
        tabs = new ArrayList<>();
        adapter = new GoodListenerTeaseViewpagerAdapter(getSupportFragmentManager(), tabs);

        mViewPager.setAdapter(adapter);
        //  第三步：将ViewPager与TableLayout 绑定在一起
        mTabLayout.setupWithViewPager(mViewPager);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                MobclickAgent.onEvent(getContext(),MobClickHelper.VSOCIAL_TAB,"vsocial_tab_"+position);

//                if (position == 0){
//                }else if (position == 1){
//                    MobclickAgent.onEvent(getContext(),MobClickHelper.VSOCIAL_TAB,"vsocial_tab_1");
//                }else if (position == 2){
//                    MobclickAgent.onEvent(getContext(),MobClickHelper.VSOCIAL_TAB,"vsocial_tab_2");
//                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_right:
                if (!SPUtils.isLogined()){
                    Intent intent = new Intent(getContext(), LoginRegistActivity.class);
                    startActivity(intent);
                }else {
                    MobclickAgent.onEvent(getContext(),MobClickHelper.VSOCIAL_PUBLIC);
                    Intent intent = new Intent(getContext(), RecordActivity.class);
                    intent.putExtra("type", "tease");
                    startActivity(intent);
                }
                break;
        }
    }
}
